package day02;

/**
 * 给定一个仅包含0 和 1 、大小为 rows x cols 的二维二进制矩阵，找出只包含 1 的最大矩形，并返回其面积。
 * <p>
 * <p>
 * <p>
 * 示例 1：
 * <p>
 * <p>
 * 输入：matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
 * 输出：6
 * 解释：最大矩形如上图所示。
 * 示例 2：
 * <p>
 * 输入：matrix = []
 * 输出：0
 * 示例 3：
 * <p>
 * 输入：matrix = [["0"]]
 * 输出：0
 * 示例 4：
 * <p>
 * 输入：matrix = [["1"]]
 * 输出：1
 * 示例 5：
 * <p>
 * 输入：matrix = [["0","0"]]
 * 输出：0
 */
public class Solution6 {
    public int maximalRectangle(char[][] matrix) {
        int m = matrix.length;
        if (m == 0) {
            return 0;
        }
        int n = matrix[0].length;
        int[][] dp = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i >= 1 && matrix[i][j] == '1' && dp[i - 1][j] >= 1) {
                    dp[i][j] = dp[i - 1][j] + 1;
                } else if (i >= 1 && matrix[i][j] == '1' && dp[i - 1][j] < 1) {
                    dp[i][j] = 1;
                } else if (i < 1 && matrix[i][j] == '1') {
                    dp[i][j] = 1;
                }
            }
        }
        int area = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (dp[i][j] == 0) {
                    continue;
                }

                int curHeigth = dp[i][j];
                for (int k = j; k >= 0 && dp[i][k] != 0; k--) {
                    int curWidth = j - k + 1;
                    curHeigth = Math.min(curHeigth, dp[i][k]);
                    area = Math.max(area, Math.max(dp[i][k], curHeigth * curWidth));
                }
            }
        }
        return area;
    }
}
